<template>
  <div class="order-page-container">
    <h3 class="page-title">您的订单</h3>

    <!-- Summary Section -->
    <div class="summary-section">
      <template v-for="(item, index) in summaryData" :key="item.label">
        <div class="summary-item">
          <span class="label">{{ item.label }}</span>
          <span class="value">{{ item.value }}</span>
        </div>
        <div v-if="index < summaryData.length - 1" class="separator"></div>
      </template>
    </div>

    <!-- Filter Section -->
    <div class="filter-section">
      <!-- Tabs -->
      <div class="filter-tabs">
        <span
          v-for="tab in tabs"
          :key="tab.name"
          :class="{ active: activeTab === tab.name }"
          @click="activeTab = tab.name"
        >
          {{ tab.label }}
        </span>
      </div>

      <!-- Filter Controls -->
      <div class="filter-controls">
        <div class="filter-row top-row">
          <div class="inputs-group">
            <el-input
              v-model="searchForm.orderNumber"
              placeholder="请输入订单编号"
              :suffix-icon="Search"
              clearable
            />
            <el-select v-model="searchForm.status">
              <template #prefix>
                <span style="color: #606266; margin-left: 5px;">订单状态</span>
              </template>
              <el-option label="全部" value="all"/>
              <el-option label="生产中" value="producing"/>
              <el-option label="已完成" value="completed"/>
              <el-option label="已关闭" value="closed"/>
            </el-select>
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="—"
              start-placeholder="下单日期"
              end-placeholder="结束日期"
              format="YYYYMMDD"
              value-format="YYYY-MM-DD"
            />
          </div>
          <el-icon class="fullscreen-icon" :size="20"><FullScreen /></el-icon>
        </div>

        <div class="filter-row bottom-row">
          <a href.prevent="#" class="collapse-link">
            收起筛选选项 <el-icon><ArrowUp /></el-icon>
          </a>
          <div class="buttons-group">
            <el-button>批量导出</el-button>
            <el-button class="search-button" @click="handleSearch">搜索</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- Main Content Area -->
       <div class="content-area">
      <!-- 替换原有el-empty为el-table -->
     <div
      class="order-list-container"
    >
      <!-- 如果没有在加载中，并且有订单数据，则显示订单列表 -->
      <template v-if="orderList.length > 0">
        <OrderCard
          v-for="order in orderList"
          :key="order.orderId"
          :order="order"
          @view-details="handleViewDetails"
        />
      </template>

      <!-- 如果没有在加载中，并且没有订单数据，则显示空状态提示 -->
      <el-empty
        v-if="orderList.length === 0"
        description="暂无订单数据"
      />
    </div>
    </div>

    <!-- 新增分页组件 -->
    <div class="pagination-container" v-if="pagination.total > 0">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        layout="prev, pager, next, jumper, ->, total"
      />
    </div>

    <OrderDetailDialog
    v-model="detailDialogVisible"
    :order-id="selectedOrderId"
  />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { Search, FullScreen, ArrowUp } from '@element-plus/icons-vue';
import { OrderApi } from '@/api/ordermange';

// ... 其他 import ...
import OrderDetailDialog from './OrderDetailDialog.vue'; // 引入组件

// --- State ---
const detailDialogVisible = ref(false);
const selectedOrderId = ref<string | null>(null);

// 新增：订单列表数据
const orderList = ref<any[]>([]);
// 新增：分页信息（当前页、每页数量、总条数）
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// Summary data
const summaryData = ref([
  { label: '近3个月', value: 0 },
  { label: '生产中', value: 0 },
  { label: '已完成', value: 0 },
  { label: '已关闭', value: 0 },
  { label: '3个月前', value: 0 },
])

const fetchOrderCount = async () => {
  const res = await OrderApi.getOrderCount()
  if (res) { 
    summaryData.value = [
      { label: '近3个月', value: res.pastThreeMonthsOrderCount || 0 },
      { label: '生产中', value: res.processingOrderCount || 0 },
      { label: '已完成', value: res.completedOrderCount || 0 },
      { label: '已关闭', value: res.closedOrderCount || 0 },
      { label: '3个月前', value: res.threeMonthOrderAgoCount || 0 },
    ]
  }
}

onMounted(() => {
fetchOrderList();
  fetchOrderCount()
})


// Tab data
const tabs = [
  { name: 'recent', label: '近3个月' },
  { name: 'production', label: '生产中' },
  { name: 'completed', label: '已完成' },
  { name: 'closed', label: '已关闭' },
  { name: 'older', label: '3个月前' },
];
const activeTab = ref('recent');

// Search form data
const initialFormState = {
  orderNumber: '',
  status: 'all',
  dateRange: ['2025-03-01', '2025-05-01'] as [string, string],
};
const searchForm = reactive({ ...initialFormState });

// --- Methods ---

const handleSearch = () => {
  console.log('Searching with:', JSON.parse(JSON.stringify(searchForm)));
  // Implement search logic here
};

const resetForm = () => {
  Object.assign(searchForm, initialFormState);
  console.log('Form has been reset.');
};

const fetchOrderList = async () => {
  const params = {
    tab: activeTab.value,  // 传递选中的标签
    // ...searchForm,         // 传递搜索表单参数
    pageNo: pagination.value.currentPage,  // 分页参数
    pageSize: pagination.value.pageSize
  };
  const res = await OrderApi.getOrderPage(params);  // 调用分页接口
  if (res) {
    orderList.value = res.list;       // 填充表格数据
    pagination.value.total = res.total; // 更新总条数
  }
};

const handleCurrentChange = (page: number) => {
  pagination.value.currentPage = page;
  fetchOrderList();
};

const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;  // 切换每页数量时重置为第一页
  fetchOrderList();
};

const handleViewDetails = (orderId: string) => {
  selectedOrderId.value = orderId;
  detailDialogVisible.value = true;
};
</script>

<style scoped>
.order-page-container {
  padding: 24px;
  background-color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
}

.page-title {
  font-size: 1.25rem; /* 20px */
  font-weight: 600;
  margin: 0 0 20px 0;
  color: #303133;
}

/* Summary Section */
.summary-section {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px 0;
  margin-bottom: 24px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-grow: 1;
}

.summary-item .label {
  font-size: 0.875rem; /* 14px */
  color: #606266;
  margin-bottom: 8px;
}

.summary-item .value {
  font-size: 2rem; /* 32px */
  font-weight: bold;
  color: #303133;
}

.separator {
  width: 1px;
  height: 50px;
  background-color: #e4e7ed;
}

/* Filter Section */
.filter-section {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 24px;
}

.filter-tabs {
  display: flex;
  gap: 32px;
  padding: 0 20px;
  border-bottom: 1px solid #e4e7ed;
}

.filter-tabs span {
  font-size: 0.875rem; /* 14px */
  color: #303133;
  padding: 16px 0;
  cursor: pointer;
  position: relative;
  border-bottom: 2px solid transparent;
}

.filter-tabs span.active {
  color: #67c23a;
  border-bottom-color: #67c23a;
}

.filter-controls {
  padding: 20px;
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-row.top-row {
  margin-bottom: 16px;
}

.inputs-group {
  display: flex;
  gap: 16px;
  align-items: center;
}

/* Customizing Element Plus components */
.inputs-group .el-input,
.inputs-group .el-select {
  width: 240px;
}
.inputs-group .el-date-editor {
  width: 260px;
}

/* Specific fix for select with prefix */
:deep(.el-select .el-input__prefix) {
    display: flex;
    align-items: center;
}

.fullscreen-icon {
  color: #909399;
  cursor: pointer;
}

.collapse-link {
  color: #909399;
  text-decoration: none;
  font-size: 0.875rem; /* 14px */
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.collapse-link:hover {
    color: #409eff;
}

.buttons-group {
  display: flex;
  gap: 10px;
}

.search-button {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}
.search-button:hover, .search-button:focus {
  background-color: #85ce61;
  border-color: #85ce61;
  color: white;
}


/* Content Area */
.content-area {
  min-height: 300px;
  display: flex;          /* 启用flex布局 */
  flex-direction: column; /* 子元素垂直排列 */
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
}

/* 新增分页容器样式 */
.pagination-container {
  margin-top: 16px;
  padding: 0 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格内容区域填充剩余空间 */
.el-table {
  flex: 1; /* 让表格占据剩余空间，分页固定在底部 */
}

/* 分页容器样式调整（保持右对齐） */
.pagination-container {
  margin: 16px 20px; /* 调整上下边距 */
  display: flex;
  justify-content: flex-end;
}
</style>
